from typing import Dict, List, Any, Optional
from dataclasses import dataclass
from enum import Enum
import scrapy
from scrapy_playwright.page import PageMethod


class ActionType(Enum):
    CLICK = "click"
    WAIT_FOR_SELECTOR = "wait_for_selector"
    WAIT_FOR_LOAD_STATE = "wait_for_load_state"
    SCROLL = "scroll"
    FILL = "fill"
    EVALUATE = "evaluate"
    SCREENSHOT = "screenshot"


@dataclass
class BrowserAction:
    action_type: ActionType
    selector: Optional[str] = None
    value: Optional[Any] = None
    timeout: Optional[int] = None
    wait_until: Optional[str] = None


class TaskTemplate:
    """浏览器任务模板"""

    def __init__(self, task_id: str, url: str, actions: List[BrowserAction]):
        self.task_id = task_id
        self.url = url
        self.actions = actions

    def to_playwright_meta(self) -> Dict[str, Any]:
        """转换为 Playwright meta 配置"""
        page_methods = []

        for action in self.actions:
            if action.action_type == ActionType.CLICK:
                page_methods.append(
                    PageMethod('click', selector=action.selector)
                )
            elif action.action_type == ActionType.WAIT_FOR_SELECTOR:
                page_methods.append(
                    PageMethod('wait_for_selector', selector=action.selector, timeout=action.timeout)
                )
            elif action.action_type == ActionType.SCROLL:
                page_methods.append(
                    PageMethod('evaluate', 'window.scrollTo(0, document.body.scrollHeight)')
                )
            elif action.action_type == ActionType.FILL:
                page_methods.append(
                    PageMethod('fill', selector=action.selector, value=action.value)
                )

        return {
            'playwright': True,
            'playwright_include_page': True,
            'playwright_page_methods': page_methods,
            'task_id': self.task_id
        }